package com.yisin.commun.modal;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

import com.alibaba.fastjson.JSONObject;

/**
 * 数据包对象，WebSocket、Socket统一的数据报文对象 文本数据传输格式统一为JSON
 * 
 * @author Yisin
 */
public class DataPackage {
	private Data data = null;
	
	public DataPackage(){
		this.data = new Data();
	}

	public DataPackage(DataType type, String req, Object content) {
		this.data = new Data(type, req, content);
	}

	public DataPackage(String req, String content) {
		this.data = new Data(req, content);
	}

	public DataPackage(String req, byte[] byteData) {
		this.data = new Data(DataType.BYTE, req, byteData);
	}
	
	public DataPackage(String req, MessageData content) {
		this.data = new Data(req, content);
	}

	public DataPackage(String req, MessageByteData content) {
		this.data = new Data(req, content);
	}

	public DataPackage(MessageData content) {
		this.data = new Data(DataConstant.REQUEST_MESSAGE, content);
	}

	public DataPackage(MessageByteData content) {
		this.data = new Data(DataType.BYTE, DataConstant.REQUEST_FILE, content);
	}

	public DataPackage(Data data) {
		this.data = data;
	}

	public DataType getDataType() {
		return null != data ? data.getType() : DataType.TEXT;
	}

	public String toString() {
		if (data != null) {
			return JSONObject.toJSONString(data);
		}
		return null;
	}
	
	public byte[] getByte(){
		return toString().getBytes();
	}
	
	public Data getData() {
		return data;
	}
	
	public DataPackage setData(Object data){
		if(this.data != null){
			this.data.setValue(data);
		}
		return this;
	}

	public String getReq() {
		return data.getReq();
	}

	public DataPackage setReq(String req) {
		this.data.setReq(req);
		return this;
	}

	/**
	 * 数据类型是否为字节数组
	 * 
	 * @return
	 */
	public boolean isByte() {
		return data.getType() == DataType.BYTE;
	}

	/**
	 * 数据类型是否为文本字符串
	 * 
	 * @return
	 */
	public boolean isText() {
		return data.getType() == DataType.TEXT;
	}

	/**
	 * 获取文本消息体，用于WebSocket协议文本消息体
	 * 
	 * @return
	 */
	public CharBuffer getCharBuffer() {
		char[] chars = toString().toCharArray();
		return CharBuffer.wrap(chars, 0, chars.length);
	}
	
	/**
	 * 获取文本消息体，用于WebSocket协议文本消息体
	 * 
	 * @return
	 */
	public ByteBuffer getByteBuffer() {
		byte[] bytes = toString().getBytes();
		return ByteBuffer.wrap(bytes, 0, bytes.length);
	}
	
	private class _DataPackage {
		
	}
}
